package com.pkx.guide.info.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pkx.guide.common.constant.Constants;
import com.pkx.guide.common.enums.ProtocolEnum;
import com.pkx.guide.common.util.DateUtils;
import com.pkx.guide.common.util.StringUtils;
import com.pkx.guide.common.util.VmsUtils;
import com.pkx.guide.fcms.service.FcmsPlayService;
import com.pkx.guide.info.domian.MbsAttribute;
import com.pkx.guide.info.entity.*;
import com.pkx.guide.info.mapper.TInfoGuidePublishMapper;
import com.pkx.guide.info.mapper.TInfoGuidePublishTaskMapper;
import com.pkx.guide.info.service.*;
import com.pkx.guide.qianfeng.service.QianFengPlayLedService;
import com.pkx.guide.record.entity.TRecordGuidePublish;
import com.pkx.guide.record.entity.TRecordGuidePublishTask;
import com.pkx.guide.record.service.TRecordGuidePublishService;
import com.pkx.guide.record.service.TRecordGuidePublishTaskService;
import com.pkx.guide.record.service.TRecordGuideStatusService;
import com.pkx.guide.task.AutoPublishTimeTask;
import com.pkx.guide.timing.ProtocolClient;
import com.sansi.tools.RetrunData;
import com.serotonin.modbus4j.code.DataType;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;

/**
 * 诱导屏发布信息表 服务实现类
 *
 * @author sunsy
 * @since 2023-11-14
 */
@Service
@Slf4j
public class TInfoGuidePublishServiceImpl extends ServiceImpl<TInfoGuidePublishMapper, TInfoGuidePublish> implements TInfoGuidePublishService {

    @Resource
    private TInfoGuideService guideService;

    @Resource
    private SansiService sansiService;

    @Resource
    private ModbusService modbusService;

    @Resource
    private TRecordGuideStatusService recordGuideStatusService;

    @Resource
    private TRecordGuidePublishService recordGuidePublishService;

    @Resource
    private TRecordGuidePublishTaskService guidePublishTaskService;

    @Resource
    private TInfoGuidePlayListService guidePlayListService;

    @Resource
    private FcmsPlayService fcmsPlayService;

    @Resource
    private TInfoNetworkConfigService infoNetworkConfigService;

    @Resource
    private QianFengPlayLedService qianFengPlayLedService;

    @Resource
    private TInfoGuideStatusService tInfoGuideStatusService;


//    @Autowired
//    private TInfoGuidePublishTaskMapper tInfoGuidePublishTaskMapper;

    /**
     * 分页列表
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public IPage<TInfoGuidePublish> pageList(Page page, TInfoGuidePublish tInfoGuidePublish) {
        LambdaQueryWrapper<TInfoGuidePublish> lambdaQueryWrapper = new QueryWrapper<TInfoGuidePublish>().lambda();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(tInfoGuidePublish.getGuidNo()), TInfoGuidePublish::getGuidNo, tInfoGuidePublish.getGuidNo());
        lambdaQueryWrapper.eq(tInfoGuidePublish.getModeType() != null, TInfoGuidePublish::getModeType, tInfoGuidePublish.getModeType());
        lambdaQueryWrapper.eq(TInfoGuidePublish::getDelFlg, 0);
        lambdaQueryWrapper.orderByAsc(TInfoGuidePublish::getModeType);
        lambdaQueryWrapper.orderByDesc(TInfoGuidePublish::getCreateTime);

        return page(page, lambdaQueryWrapper);
    }

    /**
     * 列表查询
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public List<TInfoGuidePublish> listByEntity(TInfoGuidePublish tInfoGuidePublish) {
        LambdaQueryWrapper<TInfoGuidePublish> lambdaQueryWrapper = new QueryWrapper<TInfoGuidePublish>().lambda();
        lambdaQueryWrapper.eq(tInfoGuidePublish.getGuideId() != null, TInfoGuidePublish::getGuideId, tInfoGuidePublish.getGuideId());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(tInfoGuidePublish.getGuidNo()), TInfoGuidePublish::getGuidNo, tInfoGuidePublish.getGuidNo());
        lambdaQueryWrapper.eq(tInfoGuidePublish.getModeType() != null, TInfoGuidePublish::getModeType, tInfoGuidePublish.getModeType());
        lambdaQueryWrapper.eq(TInfoGuidePublish::getDelFlg, 0);
        lambdaQueryWrapper.orderByDesc(TInfoGuidePublish::getCreateTime);
        return list(lambdaQueryWrapper);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public TInfoGuidePublish selectById(Integer id) {
        return getById(id);
    }

    /**
     * 保存
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveTInfoGuidePublish(TInfoGuidePublish tInfoGuidePublish) throws Exception {
        if (tInfoGuidePublish == null || tInfoGuidePublish.getGuideType() == null){
            throw new IllegalArgumentException("参数为空");
        }
        Integer guideType = tInfoGuidePublish.getGuideType();
        return switch (guideType) {
            case 0 -> saveSanSiGuidePublish(tInfoGuidePublish);
            case 1 -> saveQianFengGuidePublish(tInfoGuidePublish);
            default -> false;
        };
    }
    private Thread consumerThread;


    /**
     * 保存
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSanSiGuidePublish(TInfoGuidePublish tInfoGuidePublish){
        if (tInfoGuidePublish == null){
            throw new IllegalArgumentException("参数为空");
        }
        tInfoGuidePublish.setPublishTime(DateUtils.getCurrentTimeStr());
        // 查询情报板信息
        TInfoGuide guide = guideService.selectById(tInfoGuidePublish.getGuideId());
        if (guide == null){
            throw new RuntimeException("未查询到情报板信息");
        }
        // 自定义播放表
//        if (tInfoGuidePublish.getPlayListType() != null && tInfoGuidePublish.getPlayListType() == 1){
//            // 主键id置空
//            if (tInfoGuidePublish.getGuidePlayList() != null
//                    && tInfoGuidePublish.getGuidePlayList().getGuidePlayItem() != null){
//                tInfoGuidePublish.getGuidePlayList().setId(null);
//                tInfoGuidePublish.getGuidePlayList().getGuidePlayItem().setId(null);
//            }
//            // 创建播放表
//            TInfoGuidePlayList guidePlayList = guidePlayListService.savePlayList(tInfoGuidePublish.getGuidePlayList());
//            guide.setGuidePlayList(guidePlayList);
//            // 上传播放表
            fcmsPlayService.fcmsUploadPlayList(guide);
//            tInfoGuidePublish.setPlayListId(guidePlayList.getId());
//            tInfoGuidePublish.setPlayListName(guidePlayList.getName());
//        }
        save(tInfoGuidePublish);
        Integer guidePublishId = tInfoGuidePublish.getId();
        if (tInfoGuidePublish.getIsPublish() == 1){
            // 手动模式，直接发布
            if (tInfoGuidePublish.getModeType() == 1){
                RetrunData result = fcmsPlayService.fcmsActivePlayList(guide, tInfoGuidePublish.getPlayListName());
                log.info("手动发布结果：{}", JSONObject.toJSONString(result));
            } // 自动模式，通过定时任务发布
            else {
                // 发布时间
                String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                // 获取年
                int year = calendar.get(Calendar.YEAR);
                // 获取月份，0表示1月份
                int month = calendar.get(Calendar.MONTH) + 1;
                // 获取当前天数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date publishTime = null;
                try {
                    publishTime =  format.parse( year + "-" + month + "-" + day + " " + publishTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return false;
                }
                Timer timer = new Timer();
                AutoPublishTimeTask autoPublishTimeTask = new AutoPublishTimeTask(this, fcmsPlayService, tInfoGuidePublish.getId(), guide, timer);
                // 设置每24小时循环一次 24h -> 86400000ms
                timer.schedule(autoPublishTimeTask, publishTime, 86400000);
                Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
                // 保存发布任务，防止程序重启时，任务失效
                TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
                tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
                tRecordGuidePublishTask.setPublishTime(publishTime);
                tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
                tRecordGuidePublishTask.setPeriod(86400000L);
                guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);
            }
            TRecordGuidePublish tGuiGuidePublishRecord = new TRecordGuidePublish();
            // 复制发布记录对象
            BeanUtils.copyProperties(tInfoGuidePublish, tGuiGuidePublishRecord);
            tGuiGuidePublishRecord.setGuidePublishId(guidePublishId);
            tGuiGuidePublishRecord.setOperateType(0);
            tGuiGuidePublishRecord.setId(null);
            tGuiGuidePublishRecord.setImageUrl(tInfoGuidePublish.getImgId());
            // 保存发布记录
            recordGuidePublishService.saveTRecordGuidePublish(tGuiGuidePublishRecord);


        }
        return true;
    }

    /**
     * 批量保存
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveBatchGuidePublish(TInfoGuidePublish tInfoGuidePublish) throws Exception{
        if (tInfoGuidePublish == null){
            throw new IllegalArgumentException("参数为空");
        }
        if (StringUtils.isEmpty(tInfoGuidePublish.getGuideIds()) || StringUtils.isEmpty(tInfoGuidePublish.getGuidNos())){
            throw new IllegalArgumentException("未选择设备");
        }
        String[] guideIds = tInfoGuidePublish.getGuideIds().split(",");
        String[] guidNos = tInfoGuidePublish.getGuidNos().split(",");
        int i = 0;
        for (String guideId : guideIds) {
            tInfoGuidePublish.setGuideId(Integer.valueOf(guideId));
            tInfoGuidePublish.setGuidNo(guidNos[i]);
            saveSanSiGuidePublish(tInfoGuidePublish);
            tInfoGuidePublish.setId(null);
            i++;
        }
        return true;
    }
        @Autowired
         private ProtocolClient protocolClient;
        @Autowired
         private TInfoGuidePublishTaskMapper tInfoGuidePublishTaskMapper;
    /**
     * 保存-乾丰
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveQianFengGuidePublish(TInfoGuidePublish tInfoGuidePublish) throws Exception {
        if (tInfoGuidePublish == null || StringUtils.isEmpty(tInfoGuidePublish.getPublishDetail())) {
            throw new IllegalArgumentException("参数为空");
        }
        tInfoGuidePublish.setPublishTime(DateUtils.getCurrentTimeStr());
        save(tInfoGuidePublish);


        tInfoGuidePublishTaskMapper.inserts(tInfoGuidePublish);
        // 查询乾丰上位机网络配置
        TInfoNetworkConfig networkConfig = infoNetworkConfigService.selectByGuideType(1);
        if (networkConfig == null) {
            throw new RuntimeException("未查询到网络配置信息");
        }
       log.error("networkConfig：{}"+networkConfig);
        JSONObject param = new JSONObject();
        param.put("user", networkConfig.getUsername());
        param.put("pwd", networkConfig.getPassword());
        param.put("cmd", "1");
        // 先解析原始长数组，后续分批使用
        JSONArray originalPublishDetail = JSONArray.parseArray(tInfoGuidePublish.getPublishDetail());
        param.put("data", originalPublishDetail); // 原param保留，不影响其他逻辑
        log.error("param:{}"+param);
        Integer guidePublishId = tInfoGuidePublish.getId();
        boolean isPublishSuccess = true; // 标记整体发布结果

        if (tInfoGuidePublish.getIsPublish() == 1) {

            if (tInfoGuidePublish.getModeType() == 1) {
//                ProducerQest producerQest = new ProducerQest();
//                producerQest.setTask(tInfoGuidePublish);
//                producerQest.setParam(param);
//                producerQest.setNetworkConfig(networkConfig);
//                producerQest.setIpList(originalPublishDetail.toJSONString());
//                producerQest.setIpListSize((int) originalPublishDetail.size());
//                dataQueue.put(producerQest);
//                    // 4. 发送当前批次并校验结果
//                    String batchResult = qianFengPlayLedService.controlLed(
//                            networkConfig.getIp(),
//                            networkConfig.getPort(),
//                            param.toJSONString()
//                    );
//                TInfoGuidePublishTask tInfoGuidePublishTask = turnTInfoGuidePublishToTInfoGuidePublishTask(tInfoGuidePublish);
                protocolClient.sendAutoPublishData(tInfoGuidePublish);

                    log.error("batchResult：{}"+tInfoGuidePublish);
                    // 6. 批次成功后，更新该批次的情报板状态
                    tInfoGuideStatusService.updateGuideStatus(originalPublishDetail.toJSONString());
            }
            else {
                // 发布时间处理
                String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date publishTime = null;
                try {
                    publishTime = format.parse(year + "-" + month + "-" + day + " " + publishTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return false;
                }

                Timer timer = new Timer();
                // QianFengAutoPublishTimeTask autoPublishTimeTask = new QianFengAutoPublishTimeTask(this, qianFengPlayLedService, tInfoGuidePublish.getId(), networkConfig, timer);
                // timer.schedule(autoPublishTimeTask, publishTime, 86400000);
                Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);

//                // 保存自动发布任务记录
//                TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
//                tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
//                tRecordGuidePublishTask.setPublishTime(publishTime);
//                tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
//                tRecordGuidePublishTask.setPeriod(86400000L);
//                guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);
//                Runnable task = () -> {
//                    QianFengAutomatic qianFengAutomatic = new QianFengAutomatic();
//                    qianFengAutomatic.autoPublishByDate();
//                };
//                taskManager.addTask( tInfoGuidePublish.getId().toString(),timeToCron(tInfoGuidePublish.getStartTimeScale()), task);
//                 log.info("定时发布任务已保存");



            }

             // 保存发布记录（手动/自动模式都会执行，保持原有逻辑）
           TRecordGuidePublish tGuiGuidePublishRecord = new TRecordGuidePublish();
            BeanUtils.copyProperties(tInfoGuidePublish, tGuiGuidePublishRecord);
            tGuiGuidePublishRecord.setGuidePublishId(guidePublishId);
            tGuiGuidePublishRecord.setOperateType(0);
            tGuiGuidePublishRecord.setId(null);
            recordGuidePublishService.saveTRecordGuidePublish(tGuiGuidePublishRecord);
        }

        return true; // 返回整体发布结果
    }

    public static TInfoGuidePublishTask turnTInfoGuidePublishToTInfoGuidePublishTask(TInfoGuidePublish tInfoGuidePublish) {
        TInfoGuidePublishTask tInfoGuidePublishTask = new TInfoGuidePublishTask();
        tInfoGuidePublishTask.setId(tInfoGuidePublish.getId());
        tInfoGuidePublishTask.setPublishDetail(tInfoGuidePublish.getPublishDetail());
        tInfoGuidePublishTask.setIsPublish(tInfoGuidePublish.getIsPublish());
        tInfoGuidePublishTask.setModeType(tInfoGuidePublish.getModeType());
        tInfoGuidePublishTask.setStartTimeScale(tInfoGuidePublish.getStartTimeScale());
        tInfoGuidePublishTask.setEndTimeScale(tInfoGuidePublish.getEndTimeScale());
        tInfoGuidePublishTask.setDelFlg(tInfoGuidePublish.getDelFlg());
        tInfoGuidePublishTask.setState(tInfoGuidePublish.getState());
        tInfoGuidePublishTask.setCreateTime(tInfoGuidePublish.getCreateTime());
        tInfoGuidePublishTask.setUpdateTime(tInfoGuidePublish.getUpdateTime());
        //tInfoGuidePublishTask.user
//        tInfoGuidePublishTask.setCreateUser(tInfoGuidePublish.getCreateUser());
//        tInfoGuidePublishTask.setUpdateUser(tInfoGuidePublish.getUpdateUser());
//        tInfoGuidePublishTask.setDelUser(tInfoGuidePublish.getDelUser());
//        tInfoGuidePublishTask.setDelTime(tInfoGuidePublish.getDelTime());
//        tInfoGuidePublishTask.setVersion(tInfoGuidePublish.getVersion());
        return tInfoGuidePublishTask;
    }
    public static String timeToCron(String time) {
        LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm"));
        int currentMinute = localTime.getMinute();
        int currentHour = localTime.getHour();

        int targetMinute = currentMinute - 5;
        int targetHour = currentHour;

// 处理分钟为负数的情况（跨小时）
        if (targetMinute < 0) {
            targetMinute += 60; // 分钟加上60（例如 -5 + 60 = 55）
            targetHour -= 1;    // 小时减1
            // 处理小时为负数的情况（跨天，比如当前是0时，减1后为-1，需要转为前一天的23时）
            if (targetHour < 0) {
                targetHour = 23;
                // 如果需要跨天，还需额外处理日期（cron表达式的日期字段可能需要调整）
            }
        }
        log.info("目标时间：{}", String.format("0 %d %d * * ?", targetMinute, targetHour));
        return String.format("0 %d %d * * ?", targetMinute, targetHour);
    }
    /**
     * 修改
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modify(TInfoGuidePublish tInfoGuidePublish) throws Exception {
        if (tInfoGuidePublish == null || tInfoGuidePublish.getGuideType() == null){
            throw new IllegalArgumentException("参数为空");
        }
        Integer guideType = tInfoGuidePublish.getGuideType();
        return switch (guideType) {
            case 0 -> modifySanSiGuidePublish(tInfoGuidePublish);
            case 1 -> modifyQianFengGuidePublish(tInfoGuidePublish);
            default -> false;
        };
    }

    /**
     * 修改-三思
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifySanSiGuidePublish(TInfoGuidePublish tInfoGuidePublish){
        tInfoGuidePublish.setPublishTime(DateUtils.getCurrentTimeStr());
        // 查询情报板信息
        TInfoGuide guide = guideService.selectById(tInfoGuidePublish.getGuideId());
        if (guide == null){
            throw new RuntimeException("未查询到情报板信息");
        }
        // 自定义播放表
        if (tInfoGuidePublish.getPlayListType() != null && tInfoGuidePublish.getPlayListType() == 1){
            // 主键id置空
            if (tInfoGuidePublish.getGuidePlayList() != null
                    && tInfoGuidePublish.getGuidePlayList().getGuidePlayItem() != null){
                tInfoGuidePublish.getGuidePlayList().setId(null);
                tInfoGuidePublish.getGuidePlayList().getGuidePlayItem().setId(null);
            }
            // 创建播放表
            TInfoGuidePlayList guidePlayList = guidePlayListService.savePlayList(tInfoGuidePublish.getGuidePlayList());
            guide.setGuidePlayList(guidePlayList);
            // 上传播放表
            fcmsPlayService.fcmsUploadPlayList(guide);
            tInfoGuidePublish.setPlayListId(guidePlayList.getId());
            tInfoGuidePublish.setPlayListName(guidePlayList.getName());
        }
        updateById(tInfoGuidePublish);
        Integer guidePublishId = tInfoGuidePublish.getId();
        if (tInfoGuidePublish.getIsPublish() == 1){
            // 手动模式，直接发布
            if (tInfoGuidePublish.getModeType() == 1){
                fcmsPlayService.fcmsActivePlayList(guide, tInfoGuidePublish.getPlayListName());
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null){
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                // 删除发布任务
                guidePublishTaskService.deleteByGuidePublishId(guidePublishId);
            } // 自动模式，通过定时任务发布
            else {
                // 发布时间
                String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                //获取年
                int year = calendar.get(Calendar.YEAR);
                //获取月份，0表示1月份
                int month = calendar.get(Calendar.MONTH) + 1;
                //获取当前天数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date publishTime = null;
                try {
                    publishTime =  format.parse( year + "-" + month + "-" + day + " " + publishTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return false;
                }
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null){
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                Timer timer = new Timer();
                AutoPublishTimeTask autoPublishTimeTask = new AutoPublishTimeTask(this, fcmsPlayService, tInfoGuidePublish.getId(), guide, timer);
                // 设置每24小时循环一次 24h -> 86400000ms
                timer.schedule(autoPublishTimeTask, publishTime, 86400000);
                Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
                // 保存发布任务，防止程序重启时，任务失效
                TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
                tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
                tRecordGuidePublishTask.setPublishTime(publishTime);
                tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
                tRecordGuidePublishTask.setPeriod(86400000L);
                guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);
            }
            TRecordGuidePublish tGuiGuidePublishRecord = new TRecordGuidePublish();
            // 复制发布记录对象
            BeanUtils.copyProperties(tInfoGuidePublish, tGuiGuidePublishRecord);
            tGuiGuidePublishRecord.setGuidePublishId(guidePublishId);
            tGuiGuidePublishRecord.setOperateType(0);
            tGuiGuidePublishRecord.setId(null);
            // 保存发布记录
            recordGuidePublishService.saveTRecordGuidePublish(tGuiGuidePublishRecord);
        }
        return true;
    }

    /**
     * 修改-乾丰
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyQianFengGuidePublish(TInfoGuidePublish tInfoGuidePublish) throws Exception {
        tInfoGuidePublish.setPublishTime(DateUtils.getCurrentTimeStr());
        updateById(tInfoGuidePublish);
// 查询乾丰上位机网络配置
        TInfoNetworkConfig networkConfig = infoNetworkConfigService.selectByGuideType(1);
        if (networkConfig == null) {
            throw new RuntimeException("未查询到网络配置信息");
        }
        JSONObject param = new JSONObject();
        param.put("user", networkConfig.getUsername());
        param.put("pwd", networkConfig.getPassword());
        param.put("cmd", "1");
        Integer guidePublishId = tInfoGuidePublish.getId();
        if (tInfoGuidePublish.getIsPublish() == 1) {
            // 手动模式，直接发布
            if (tInfoGuidePublish.getModeType() == 1) {
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null) {
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                // 删除发布任务
                guidePublishTaskService.deleteByGuidePublishId(guidePublishId);

                // -------------------------- 分批次发送核心逻辑 --------------------------
                JSONArray fullDataArray = null;
                try {
                    // 1. 解析完整数组（先清理可能的非法字符，避免之前的JSON语法错误）
                    String publishDetail = tInfoGuidePublish.getPublishDetail();
                    // 清理非法内容：移除类似 (1296)xxx(ret:1) 的非JSON片段（根据实际情况调整正则）
                    String cleanedDetail = publishDetail.replaceAll("\\(\\d+\\).*?\\(ReadPrgId ret:\\d+\\)", "");
                    fullDataArray = JSONArray.parseArray(cleanedDetail);
                } catch (JSONException e) {
                    log.error("解析publishDetail数组失败", e);
                    return false;
                }
                if (fullDataArray == null || fullDataArray.isEmpty()) {
                    log.warn("publishDetail数组为空，无需发送");
                    return false;
                }

                // 2. 配置批次参数：3个一组
                int batchSize = 3;
                int totalSize = fullDataArray.size();
                // 计算总批次数（向上取整，确保最后一批不足3个也能发送）
                int totalBatches = (totalSize + batchSize - 1) / batchSize;

                // 3. 循环分批次发送
                for (int i = 0; i < totalBatches; i++) {
                    // 计算当前批次的起始和结束索引（避免越界）
                    int startIndex = i * batchSize;
                    int endIndex = Math.min((i + 1) * batchSize, totalSize);
                    // 截取当前批次的子数组
                    JSONArray batchArray = new JSONArray();
                    for (int j = startIndex; j < endIndex; j++) {
                        batchArray.add(fullDataArray.get(j));
                    }

                    // 4. 设置当前批次数据并发送
                    param.put("data", batchArray);
                    String result = qianFengPlayLedService.controlLed(
                            networkConfig.getIp(),
                            networkConfig.getPort(),
                            param.toJSONString()
                    );
                    log.info("手动发布第{}批结果（共{}批），发送数据：{}，返回结果：{}",
                            i + 1, totalBatches, batchArray.toJSONString(), result);

                    // 5. 校验当前批次发送结果
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if (resultJson == null || !"0".equals(resultJson.getString("code"))) {
                        log.error("第{}批发送失败，终止后续批次", i + 1);
                        return false; // 若某批次失败，终止整体流程（可根据业务调整为"继续发送其他批次"）
                    }
                }
                // -------------------------- 分批次发送核心逻辑结束 --------------------------

                // 所有批次发送成功后，更新情报板发布状态
                tInfoGuideStatusService.updateGuideStatus(tInfoGuidePublish.getPublishDetail());
            }
            // 自动模式，通过定时任务发布（原有逻辑不变）
            else {
                // 发布时间
                String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                //获取年
                int year = calendar.get(Calendar.YEAR);
                //获取月份，0表示1月份
                int month = calendar.get(Calendar.MONTH) + 1;
                //获取当前天数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date publishTime = null;
                try {
                    publishTime = format.parse(year + "-" + month + "-" + day + " " + publishTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return false;
                }
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null) {
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                Timer timer = new Timer();
                // QianFengAutoPublishTimeTask autoPublishTimeTask = new QianFengAutoPublishTimeTask(this, qianFengPlayLedService, tInfoGuidePublish.getId(), networkConfig, timer);
                // 设置每24小时循环一次 24h -> 86400000ms
                // timer.schedule(autoPublishTimeTask, publishTime, 86400000);
                Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
                // 保存发布任务，防止程序重启时，任务失效
                TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
                tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
                tRecordGuidePublishTask.setPublishTime(publishTime);
                tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
                tRecordGuidePublishTask.setPeriod(86400000L);
                guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);
            }
            // 保存发布记录（原有逻辑不变）
            TRecordGuidePublish tGuiGuidePublishRecord = new TRecordGuidePublish();
            BeanUtils.copyProperties(tInfoGuidePublish, tGuiGuidePublishRecord);
            tGuiGuidePublishRecord.setGuidePublishId(guidePublishId);
            tGuiGuidePublishRecord.setOperateType(0);
            tGuiGuidePublishRecord.setId(null);
            recordGuidePublishService.saveTRecordGuidePublish(tGuiGuidePublishRecord);
        }
        return true;
    }

    /**
     * 更改模式
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMode(TInfoGuidePublish tInfoGuidePublish) throws Exception{
        if (tInfoGuidePublish == null || tInfoGuidePublish.getGuideType() == null){
            throw new IllegalArgumentException("参数为空");
        }
        Integer guideType = tInfoGuidePublish.getGuideType();
        return switch (guideType) {
            case 0 -> updateModeSanSi(tInfoGuidePublish);
            case 1 -> updateModeQianFeng(tInfoGuidePublish);
            default -> false;
        };
    }

    /**
     * 更改模式-三思
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public Boolean updateModeSanSi(TInfoGuidePublish tInfoGuidePublish){
        tInfoGuidePublish.setPublishTime(DateUtils.getCurrentTimeStr());
        // 查询情报板信息
        TInfoGuide guide = guideService.selectById(tInfoGuidePublish.getGuideId());
        if (guide == null){
            throw new RuntimeException("未查询到情报板信息");
        }
        // 自定义播放表
        if (tInfoGuidePublish.getPlayListType() != null && tInfoGuidePublish.getPlayListType() == 1){
            // 主键id置空
            if (tInfoGuidePublish.getGuidePlayList() != null
                    && tInfoGuidePublish.getGuidePlayList().getGuidePlayItem() != null){
                tInfoGuidePublish.getGuidePlayList().setId(null);
                tInfoGuidePublish.getGuidePlayList().getGuidePlayItem().setId(null);
            }
            // 创建播放表
            TInfoGuidePlayList guidePlayList = guidePlayListService.savePlayList(tInfoGuidePublish.getGuidePlayList());
            guide.setGuidePlayList(guidePlayList);
            // 上传播放表
            fcmsPlayService.fcmsUploadPlayList(guide);
            tInfoGuidePublish.setPlayListId(guidePlayList.getId());
            tInfoGuidePublish.setPlayListName(guidePlayList.getName());
        }
        updateById(tInfoGuidePublish);
        Integer guidePublishId = tInfoGuidePublish.getId();
        if (tInfoGuidePublish.getIsPublish() == 1){
            // 手动模式，直接发布
            if (tInfoGuidePublish.getModeType() == 1){
                fcmsPlayService.fcmsActivePlayList(guide, tInfoGuidePublish.getPlayListName());
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null){
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                // 删除发布任务
                guidePublishTaskService.deleteByGuidePublishId(guidePublishId);
            } // 自动模式，通过定时任务发布
            else {
                // 发布时间
                String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                //获取年
                int year = calendar.get(Calendar.YEAR);
                //获取月份，0表示1月份
                int month = calendar.get(Calendar.MONTH) + 1;
                //获取当前天数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date publishTime = null;
                try {
                    publishTime =  format.parse( year + "-" + month + "-" + day + " " + publishTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return false;
                }
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null){
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                Timer timer = new Timer();
                AutoPublishTimeTask autoPublishTimeTask = new AutoPublishTimeTask(this, fcmsPlayService, tInfoGuidePublish.getId(), guide, timer);
                // 设置每24小时循环一次 24h -> 86400000ms
                timer.schedule(autoPublishTimeTask, publishTime, 86400000);
                Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
                // 保存发布任务，防止程序重启时，任务失效
                TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
                tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
                tRecordGuidePublishTask.setPublishTime(publishTime);
                tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
                tRecordGuidePublishTask.setPeriod(86400000L);
                guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);
            }
            TRecordGuidePublish tGuiGuidePublishRecord = new TRecordGuidePublish();
            // 复制发布记录对象
            BeanUtils.copyProperties(tInfoGuidePublish, tGuiGuidePublishRecord);
            tGuiGuidePublishRecord.setGuidePublishId(guidePublishId);
            tGuiGuidePublishRecord.setOperateType(0);
            tGuiGuidePublishRecord.setId(null);
            // 保存发布记录
            recordGuidePublishService.saveTRecordGuidePublish(tGuiGuidePublishRecord);
        }
        return true;
    }

    /**
     * 更改模式-乾丰
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public Boolean updateModeQianFeng(TInfoGuidePublish tInfoGuidePublish) throws Exception{
        tInfoGuidePublish.setPublishTime(DateUtils.getCurrentTimeStr());
        updateById(tInfoGuidePublish);
        // 查询乾丰上位机网络配置
        TInfoNetworkConfig networkConfig = infoNetworkConfigService.selectByGuideType(1);
        if (networkConfig == null){
            throw new RuntimeException("未查询到网络配置信息");
        }
        JSONObject param = new JSONObject();
        param.put("user", networkConfig.getUsername());
        param.put("pwd", networkConfig.getPassword());
        param.put("cmd", 1);
        param.put("data", JSONArray.parseArray(tInfoGuidePublish.getPublishDetail()));
        Integer guidePublishId = tInfoGuidePublish.getId();
        if (tInfoGuidePublish.getIsPublish() == 1){
            // 手动模式，直接发布
            if (tInfoGuidePublish.getModeType() == 1){
                qianFengPlayLedService.controlLed(networkConfig.getIp(), networkConfig.getPort(), param.toJSONString());
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null){
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                // 删除发布任务
                guidePublishTaskService.deleteByGuidePublishId(guidePublishId);
            } // 自动模式，通过定时任务发布
            else {
                // 发布时间
                String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Calendar calendar = Calendar.getInstance();
                //获取年
                int year = calendar.get(Calendar.YEAR);
                //获取月份，0表示1月份
                int month = calendar.get(Calendar.MONTH) + 1;
                //获取当前天数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date publishTime = null;
                try {
                    publishTime =  format.parse( year + "-" + month + "-" + day + " " + publishTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return false;
                }
                // 停止上次启动的timer
                Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
                if (lastTimer != null){
                    lastTimer.cancel();
                    Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
                }
                Timer timer = new Timer();
//                QianFengAutoPublishTimeTask autoPublishTimeTask = new QianFengAutoPublishTimeTask(this, qianFengPlayLedService, tInfoGuidePublish.getId(), networkConfig, timer);
//                // 设置每24小时循环一次 24h -> 86400000ms
//                timer.schedule(autoPublishTimeTask, publishTime, 86400000);
                Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
                // 保存发布任务，防止程序重启时，任务失效
                TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
                tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
                tRecordGuidePublishTask.setPublishTime(publishTime);
                tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
                tRecordGuidePublishTask.setPeriod(86400000L);
                guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);
            }
            TRecordGuidePublish tGuiGuidePublishRecord = new TRecordGuidePublish();
            // 复制发布记录对象
            BeanUtils.copyProperties(tInfoGuidePublish, tGuiGuidePublishRecord);
            tGuiGuidePublishRecord.setGuidePublishId(guidePublishId);
            tGuiGuidePublishRecord.setOperateType(0);
            tGuiGuidePublishRecord.setId(null);
            // 保存发布记录
            recordGuidePublishService.saveTRecordGuidePublish(tGuiGuidePublishRecord);
        }
        return true;
    }

    /**
     * 停止自动执行
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean stopAutoPublish(TInfoGuidePublish tInfoGuidePublish){
        if (tInfoGuidePublish == null || tInfoGuidePublish.getId() == null){
            throw new IllegalArgumentException("参数为空");
        }
        tInfoGuidePublish.setState(1);
        updateById(tInfoGuidePublish);
        // 停止上次启动的timer
        Timer lastTimer = Constants.guidePublishTimerMap.get(tInfoGuidePublish.getId());
        if (lastTimer != null){
            lastTimer.cancel();
            Constants.guidePublishTimerMap.remove(tInfoGuidePublish.getId());
        }
        // 删除发布任务
        guidePublishTaskService.deleteByGuidePublishId(tInfoGuidePublish.getId());
        return true;
    }

    /**
     * 开启自动执行
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean startAutoPublish(TInfoGuidePublish tInfoGuidePublish){
        if (tInfoGuidePublish == null || tInfoGuidePublish.getId() == null){
            throw new IllegalArgumentException("参数为空");
        }
        tInfoGuidePublish.setState(0);
        updateById(tInfoGuidePublish);
        // 查询发布信息
        tInfoGuidePublish = selectById(tInfoGuidePublish.getId());
        if (tInfoGuidePublish == null){
            throw new RuntimeException("未查询到发布信息");
        }
        Integer guideType = tInfoGuidePublish.getGuideType();
        return switch (guideType) {
            case 0 -> startSanSiAutoPublish(tInfoGuidePublish);
            case 1 -> startQianFengAutoPublish(tInfoGuidePublish);
            default -> false;
        };
    }

    /**
     * 开启自动执行-三思
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public Boolean startSanSiAutoPublish(TInfoGuidePublish tInfoGuidePublish){
        if (tInfoGuidePublish == null || tInfoGuidePublish.getId() == null){
            throw new IllegalArgumentException("参数为空");
        }
        tInfoGuidePublish.setState(0);
        updateById(tInfoGuidePublish);
        // 查询发布信息
        tInfoGuidePublish = selectById(tInfoGuidePublish.getId());
        if (tInfoGuidePublish == null){
            throw new RuntimeException("未查询到发布信息");
        }
        // 查询情报板信息
        TInfoGuide guide = guideService.selectById(tInfoGuidePublish.getGuideId());
        if (guide == null){
            throw new RuntimeException("未查询到情报板信息");
        }
        // 发布时间
        String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar calendar = Calendar.getInstance();
        // 获取年
        int year = calendar.get(Calendar.YEAR);
        // 获取月份，0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        // 获取当前天数
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        Date publishTime = null;
        try {
            publishTime =  format.parse( year + "-" + month + "-" + day + " " + publishTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
        Date currentDate = new Date();
        // 如果发布时间已过，则加一天执行，未过，直接执行
        if (currentDate.compareTo(publishTime) > 0){
            calendar.setTime(publishTime);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            publishTime = calendar.getTime();
        }
        Timer timer = new Timer();
        AutoPublishTimeTask autoPublishTimeTask = new AutoPublishTimeTask(this, fcmsPlayService, tInfoGuidePublish.getId(), guide, timer);
        // 设置每24小时循环一次 24h -> 86400000ms
        timer.schedule(autoPublishTimeTask, publishTime, 86400000);
        Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
        // 保存发布任务，防止程序重启时，任务失效
        TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
        tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
        tRecordGuidePublishTask.setPublishTime(publishTime);
        tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
        tRecordGuidePublishTask.setPeriod(86400000L);
        guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);

        return true;
    }

    /**
     * 开启自动执行-乾丰
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public Boolean startQianFengAutoPublish(TInfoGuidePublish tInfoGuidePublish){
        if (tInfoGuidePublish == null || tInfoGuidePublish.getId() == null){
            throw new IllegalArgumentException("参数为空");
        }
        tInfoGuidePublish.setState(0);
        updateById(tInfoGuidePublish);
        // 查询发布信息
        tInfoGuidePublish = selectById(tInfoGuidePublish.getId());
        if (tInfoGuidePublish == null){
            throw new RuntimeException("未查询到发布信息");
        }
        // 查询乾丰上位机网络配置
        TInfoNetworkConfig networkConfig = infoNetworkConfigService.selectByGuideType(1);
        if (networkConfig == null){
            throw new RuntimeException("未查询到网络配置信息");
        }
        // 发布时间
        String publishTimeStr = tInfoGuidePublish.getStartTimeScale();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar calendar = Calendar.getInstance();
        // 获取年
        int year = calendar.get(Calendar.YEAR);
        // 获取月份，0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        // 获取当前天数
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        Date publishTime = null;
        try {
            publishTime =  format.parse( year + "-" + month + "-" + day + " " + publishTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
        Date currentDate = new Date();
        // 如果发布时间已过，则加一天执行，未过，直接执行
        if (currentDate.compareTo(publishTime) > 0){
            calendar.setTime(publishTime);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            publishTime = calendar.getTime();
        }
        Timer timer = new Timer();
//        QianFengAutoPublishTimeTask autoPublishTimeTask = new QianFengAutoPublishTimeTask(this, qianFengPlayLedService, tInfoGuidePublish.getId(), networkConfig, timer);
////        // 设置每24小时循环一次 24h -> 86400000ms
//        timer.schedule(autoPublishTimeTask, publishTime, 86400000);
        Constants.guidePublishTimerMap.put(tInfoGuidePublish.getId(), timer);
        // 保存发布任务，防止程序重启时，任务失效
        TRecordGuidePublishTask tRecordGuidePublishTask = new TRecordGuidePublishTask();
        tRecordGuidePublishTask.setGuidePublishId(tInfoGuidePublish.getId());
        tRecordGuidePublishTask.setPublishTime(publishTime);
        tRecordGuidePublishTask.setPublishTimeScale(publishTimeStr);
        tRecordGuidePublishTask.setPeriod(86400000L);
        guidePublishTaskService.saveTRecordGuidePublishTask(tRecordGuidePublishTask);

        return true;
    }

    /**
     * 发布图片
     *
     * @param tInfoGuidePublish
     * @return
     */
    public Boolean publish(TInfoGuidePublish tInfoGuidePublish){
        switch (tInfoGuidePublish.getPublishType()){
            case 0:
                return publishImg(tInfoGuidePublish);
            case 1:
                return publishImg(tInfoGuidePublish);
        }
        return false;
    }

    /**
     * 发布图片
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public Boolean publishImg(TInfoGuidePublish tInfoGuidePublish){
        // 生成 playlst
        String playlst = sansiService.genPlaylst(tInfoGuidePublish.getImgUrl());
        // 发布
        TInfoGuide guideInfo = guideService.selectById(tInfoGuidePublish.getGuideId());
        return sansiService.ULOneStrFile(playlst, "play.lst", guideInfo.getGuidIp(), Integer.parseInt(guideInfo.getGuidPort()), 1);
    }

    /**
     * 发布文字
     *
     * @param tInfoGuidePublish
     * @return
     */
    @Override
    public Boolean publishText(TInfoGuidePublish tInfoGuidePublish){
        if (tInfoGuidePublish == null
                || StringUtils.isEmpty(tInfoGuidePublish.getText())
                || StringUtils.isEmpty(tInfoGuidePublish.getFont())
                || StringUtils.isEmpty(tInfoGuidePublish.getFontSize())
                || StringUtils.isEmpty(tInfoGuidePublish.getFontColor())){
            return false;
        }
        // 分隔文字
        String[] textArr = tInfoGuidePublish.getText().split(";");
        String[] fontArr = tInfoGuidePublish.getFont().split(";");
        String[] fontSizeArr = tInfoGuidePublish.getFontSize().split(";");
        String[] fontColorArr = tInfoGuidePublish.getFontColor().split(";");
        if (textArr.length != fontArr.length && textArr.length != fontSizeArr.length && textArr.length != fontColorArr.length){
            return false;
        }
        // 发布
        TInfoGuide guideInfo = guideService.selectById(tInfoGuidePublish.getGuideId());
        if (guideInfo == null){
            return false;
        }
        ProtocolEnum protocol = ProtocolEnum.SWARCO_CMS_V1d5;
        String newline = "|";
        //组织报文
        StringBuilder sb = new StringBuilder();
        sb.append(" 01 01 FF FF FF FF FF FF ");
        for (int i = 0; i < textArr.length; i++){
            // 出字方式、间隔（默认：立即显示 + 5s）
            sb.append(" 1b 37 31 ");
            sb.append(" 1b 38 30 30 35 ");
            //字体、字体大小
            sb.append(" 1b 39 " + VmsUtils.fontCvt(protocol, fontArr[i]));
            sb.append(" 1b 3a " + VmsUtils.fontSizeCvt(protocol, Integer.valueOf(fontSizeArr[i])));
            //字符颜色
            sb.append(" 1b " + VmsUtils.fontColorCvt(protocol, fontColorArr[i]));
            //水平垂直对齐（默认居中）
            sb.append(" 1b 34 1b 31 ");
            //文字
            //解析<br>换行，替换为 1B 0A
            int sPos = 0, ePos = 0;
            String line = "";
            String text = StringUtils.isEmpty(textArr[i]) ? "" : textArr[i];
            ePos = text.indexOf(newline, sPos);
            try {
                while (ePos != -1) {
                    line = text.substring(sPos, ePos);
                    sb.append(StringUtils.bytesToHexStr(line.getBytes("gb2312")));
                    sb.append(" 1B 0A ");
                    sPos = ePos + newline.length();
                    ePos = text.indexOf(newline, sPos);
                }
                line = text.substring(sPos);
                sb.append(StringUtils.bytesToHexStr(line.getBytes("gb2312")));
            }catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //换屏
            sb.append("1B0D");
        }
        //去掉最后的 1B0D
        sb.delete(sb.length()-4, sb.length());
        sb.append(" 0000000000000000000000000000000000000000000000000000000000000000000000 ");

        MbsAttribute mbsAttribute = new MbsAttribute(guideInfo.getGuidIp(), Integer.valueOf(guideInfo.getGuidPort()), guideInfo.getSlaveId(),
                3, Integer.valueOf("1500", 16), 0, DataType.TWO_BYTE_INT_SIGNED);
        try {
            byte[] bytes = StringUtils.hexStrToBytes(sb.toString());
            short[] shorts = StringUtils.bytesToShorts(bytes);
            modbusService.writeMultiRegister(mbsAttribute, shorts);
        } catch (Exception e) {
            log.error("情报板发布失败：" + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Integer id) {
        if (id == null){
            return false;
        }
        LambdaUpdateWrapper<TInfoGuidePublish> lambdaUpdateWrapper = new UpdateWrapper<TInfoGuidePublish>().lambda()
            .eq(TInfoGuidePublish::getId, id)
            .set(TInfoGuidePublish::getDelFlg, 1);
        update(lambdaUpdateWrapper);
        // 停止上次启动的timer
        Timer lastTimer = Constants.guidePublishTimerMap.get(id);
        if (lastTimer != null){
            lastTimer.cancel();
            Constants.guidePublishTimerMap.remove(id);
        }
        // 删除发布任务
        guidePublishTaskService.deleteByGuidePublishId(id);
        return true;
    }

    /**
     * 查询正在执行任务
     *
     * @return
     */
    @Override
    public String getExecutingPublish(){
        return JSONObject.toJSONString(Constants.guidePublishTimerMap);
    }


}
